<template>
  <div class="mb20">
    <div class="flex-center mb12">
      <Title title="精力类型" font-size="16px"/>
      <PlainCreateBtn @click="toCreate">新建</PlainCreateBtn>
    </div>
    <u-table
      v-loading="loading"
      v-if="list && list.items.length > 0"
      ref="tableRef"
      :border="false"
      :row-height="49"
      :data="list.items"
      use-virtual
      class="fb-table"
      empty-text="暂无数据"
      fit
      row-key="id"
      hightlight-current-row>
      <u-table-column align="left" prop="energyType" label="精力类型名称" min-width="100">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.energyType"/>
        </template>
      </u-table-column>
      <u-table-column align="left" prop="energyTypeDesc" label="精力类型说明" min-width="120">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.energyTypeDesc"/>
        </template>
      </u-table-column>
      <u-table-column align="left" prop="updator" label="更新人">
        <template slot-scope="scope">
          <span>{{ scope.row.updator || '--' }}</span>
        </template>
      </u-table-column>
      <u-table-column prop="updateTime" align="left" label="更新时间" min-width="110">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.updateTime">{{ scope.row.updateTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
            <span v-else>--</span>
          </div>
        </template>
      </u-table-column>
      <u-table-column align="left" prop="creator" label="创建人">
        <template slot-scope="scope">
          <div>{{ scope.row.creator || '--' }}</div>
        </template>
      </u-table-column>
      <u-table-column prop="createTime" align="left" label="创建时间" min-width="110">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.createTime">{{ scope.row.createTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
            <span v-else>--</span>
          </div>
        </template>
      </u-table-column>
      <el-table-column
        :width="showMobilePage ? 80 : 100"
        align="center"
        fixed="right"
        label="操作">
        <template slot-scope="scope">
          <div class="operator-btn" style="padding: 0 10px;">
            <el-button type="text" @click="toEdit(scope.row)"><span style="font-size:14px;">编辑</span></el-button>
            <el-button v-if="showDelete(scope.row)" type="text" @click="toDelete(scope.row)"><span style="font-size:14px;">删除</span></el-button>
          </div>
        </template>
      </el-table-column>
    </u-table>
    <empty-placeholder v-else style="margin-bottom: 24px" />
    <el-row v-if="list.total > 0" type="flex" justify="end">
      <el-pagination
        :page-size="perPage"
        :current-page="page"
        :page-sizes="[10,20, 50, 100, 250, 500]"
        :small="showMobilePage"
        :total="list.total"
        :layout="showMobilePage ? 'prev, pager, next, jumper':'total, prev, pager, next, sizes, jumper'"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </el-row>
    <!--编辑弹窗  -->
    <el-dialog
      :visible="dialogVisible"
      :show-close="true"
      :close-on-click-modal="true"
      :close="handleClose"
      :before-close="handleClose"
      class="small-common-dialog-size operator-dialog"
    >
      <div class="title-container">
        <Title :title="`${isEdit ? '编辑' : '新建'}精力类型`" font-size="16px" style="margin-bottom: 16px;"/>
      </div>
      <el-form ref="formRef" :rules="rules" :model="editData" label-width="110px" label-position="left">
        <el-form-item label="精力类型名称" prop="energyType">
          <el-input v-model="editData.energyType" class="width240" size="small" placeholder="请输入" maxlength="200" type="text" />
        </el-form-item>
        <el-form-item label="精力类型说明" prop="energyTypeDesc">
          <el-input v-model="editData.energyTypeDesc" class="width240" size="small" placeholder="请输入" maxlength="200" type="text" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="center">
        <el-button :disabled="isSubmit" type="primary" size="small" class="ok submit-btn" @click="submit">保存</el-button>
        <el-button class="back-btn cancel-btn-style" type="info" size="small" @click="handleClose" >取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import PlainCreateBtn from '@/components/Common/baseComponent/plain-create-btn';

import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import { format } from '@/filters/date';
import { getEnergyTypeList, deleteEnergyType, editEnergyType, createEnergyType } from '@/api/setting';
import { showModal } from '@/utils/message';

export default {
  components: { EmptyPlaceholder, Title, PlainCreateBtn },
  filters: { format },
  data() {
    return {
      loading: false,
      perPage: 10,
      page: 1,
      list: {
        items: [],
        total: 0
      },
      editData: {
        energyType: '',
        energyTypeDesc: ''
      },
      dialogVisible: false,
      isSubmit: false,
      rules: {
        energyType: [{ required: true, trigger: 'blur', message: '请输入类型名称' }]
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isEdit() {
      return !!this.editData.id;
    }
  },
  created() {
    this.fetchData(true);
  },
  methods: {
    hasRouteAuth,
    // 获取列表
    fetchData(reset = false) {
      if (reset) {
        this.page = 1;
      } else {
        this.loading = true;
      }
      const params = {
        page: this.page,
        perPage: this.perPage
      };
      getEnergyTypeList(params).then(res => {
        this.loading = false;
        if (res.code === 200) { this.list = res.data; }
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    toEdit(row) {
      this.openDialog(row);
    },
    toCreate() {
      this.openDialog();
    },
    toDelete(row) {
      showModal('请确认是否删除').then(_ => {
        deleteEnergyType({ id: row.id }).then(_ => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.$emit('queryAllTypes');
        });
      });
    },
    openDialog(data = {}) {
      this.dialogVisible = true;
      this.editData = JSON.parse(JSON.stringify(data));
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate();
      });
    },
    submit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.isSubmit = true;
          const { id, energyType, energyTypeDesc } = this.editData;
          const data = {
            id,
            energyType,
            energyTypeDesc
          };
          const api = this.isEdit ? editEnergyType : createEnergyType;
          api(data).then(res => {
            this.isSubmit = false;
            if (res.code === 200) {
              this.$message.success('操作成功');
              this.handleClose();
              this.isEdit ? this.$emit('queryAllTypes') : this.fetchData();
            } else {
              this.$message.error(res.message);
            }
          }).catch(err => {
            this.isSubmit = false;
            console.log(err);
          });
        } else {
          this.$message.warning('请检查信息是否填写完整');
        }
      });
    },
    showDelete(row) {
      const hiddenTypeName = ['项目', '账号'];
      return !hiddenTypeName.includes(row.energyType);
    },
    handleClose() {
      this.$refs['formRef'].resetFields();
      this.dialogVisible = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.operator-dialog {
  ::v-deep {
    .el-dialog__body {
      padding: 24px 24px 0px 24px !important;
    }
    .el-form-item__label {
      text-align: right;
    }
  }
}
.width240 {
  width: 240px;
}
.operator-btn {
  display: flex;
  &::v-deep {
    .el-button--text:not(:first-child) {
      position: relative;
      &::before {
        content: '';
        width: 1px;
        height: 12px;
        position: absolute;
        left: -6px;
        top: 1px;
        background-color: #ddd;
      }
    }
  }
}
.center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.flex-1 {
  flex: 1;
}
.mb20 {
  margin-bottom: 20px;
}
</style>
